package com.cloud.lan.service.tx.wx;

import com.alibaba.fastjson.JSON;
import com.cloud.lan.service.tx.wx.model.WxUrlLinkReq;
import com.cloud.lan.service.tx.wx.model.WxUrlLinkRes;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhouquan on 2022/4/22.
 */
@Slf4j
@Service
public class WxCService {

    @Autowired
    private WxInitService wxInitService;

    public static final String wxDataUrl = "https://api.weixin.qq.com/wxa/generate_urllink?access_token={}";


    public WxUrlLinkRes createUrlLink(WxUrlLinkReq req){
        WxUrlLinkRes res = new WxUrlLinkRes();
        try {
            String accessToken = wxInitService.getAccessToken();
            if(req.getPath().contains("?")){
                String oriPath = req.getPath();
                String[] ary = oriPath.split("\\?");
                req.setPath(ary[0]);
                req.setQuery(ary[1]);
            }
            String url = StrUtil.format(wxDataUrl, accessToken);
            Map<String, Object> map = Convert.convert(new TypeReference<Map<String, Object>>() {}, req);
            String mapParams = JSONUtil.toJsonStr(map);
            log.info("微信urllink生成.url:[{}].params:[{}]", url, mapParams);
            String result = HttpUtil.post(url, mapParams);
            log.info("微信urllink生成.res:[{}]", JSON.toJSONString(result));
            res = JSON.parseObject(result,WxUrlLinkRes.class);
        } catch (Exception e) {
            log.error("微信urllink生成.error", e);
        }
        return res;

    }

    public static void main(String[] args){
        String str = "/pages/discovery-detail/index?id=15";
        String[] ary = str.split("\\?");
        System.out.println(JSON.toJSONString(ary));
    }
}
